package com.wtb.javatool.service.impl;

import com.wtb.javatool.dao.AttachmentMapper;
import com.wtb.javatool.entity.Attachment;
import com.wtb.javatool.service.AttachmentService;
import org.apache.commons.fileupload.FileItem;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Date;
import java.util.List;

@Service
public class AttachmentServiceImpl implements AttachmentService {

    private final AttachmentMapper attachmentMapper;

    public AttachmentServiceImpl(AttachmentMapper attachmentMapper) {
        this.attachmentMapper = attachmentMapper;
    }

    /**
     * 根据任务ID，为其添加附件,同时讲文件保存在本地
     *
     * @param taskId    任务ID
     * @param fileItems 文件列表
     */
    @Override
    public void upLoadTaskAttachment(Long taskId, Long creatorId, List<FileItem> fileItems) throws Exception {
        for (FileItem fileItem : fileItems) {
            if (!fileItem.isFormField()) { // 检查是否为文件
                Date date = new Date();
                Attachment attachment = new Attachment();

                attachment.setAttachmentName(fileItem.getName());
                attachment.setSize(fileItem.getSize());
                attachment.setCreateTime(date);
                attachment.setCreatorId(creatorId);
                attachment.setTaskId(taskId);
                attachmentMapper.uploadAttachment(attachment);

                String fileName =  attachment.getAttachmentId() + "_" + fileItem.getName() ;
                String savePath = "E:/uploads/"; // 设置保存路径

                File saveFile = new File(savePath + File.separator + fileName);
                attachment.setAttachmentUrl(saveFile.getPath());
                attachmentMapper.uploadAttachmentUrl(attachment);

                fileItem.write(saveFile); // 将文件写入到本地磁盘
            }
        }
    }

    /**
     * 根据任务ID，返回与任务相关的所有附件
     *
     * @param taskId 任务ID
     * @return 附件列表，具体参数参考Attachment实体
     */
    public List<Attachment> findAttachmentsByTaskId(Long taskId){
        return attachmentMapper.findAttachmentsByTaskId(taskId);
    }

    /**
     * 删除某个附件
     *
     * @param attachmentId 任务ID
     */
    public void deleteAttachmentByAttachmentId(Long attachmentId, String attachmentUrl) {
        try {
            // 1. 首先尝试从数据库删除附件记录
            attachmentMapper.deleteAttachmentByAttachmentId(attachmentId);
            
            // 2. 如果URL为空则直接返回
            if (attachmentUrl == null || attachmentUrl.trim().isEmpty()) {
                return;
            }
            
            // 3. 尝试删除物理文件
            try {
                // 规范化路径字符串，替换斜杠，处理路径
                String normalizedPath = attachmentUrl.replace('\\', '/');
                Path path = Paths.get(normalizedPath);
                
                // 检查文件是否存在
                if (Files.exists(path)) {
                    Files.delete(path);
                    System.out.println("成功删除文件: " + attachmentUrl);
                } else {
                    System.out.println("文件不存在，无需删除: " + attachmentUrl);
                }
            } catch (IOException e) {
                // 打印错误日志，但不影响主流程，数据库记录已删除
                System.err.println("删除文件时出错，但数据库记录已删除: " + e.getMessage());
            }
        } catch (Exception e) {
            // 发生任何其他异常时记录日志，但不阻止流程继续
            System.err.println("删除附件时发生异常: " + e.getMessage());
            e.printStackTrace();
        }
    }
}